<template>
    <div class="main-container">
        <!-- 左边区域 -->
        <div class="left-panel">
            <div class="video-section">
                <div v-if="currentVideo && !reuploading" class="video-container">
                    <video controls :src="getVideoUrl(currentVideo.video)" class="video-player"></video>
                    <div class="video-overlay">
                        <el-button type="primary" circle icon="el-icon-refresh" @click="handleReupload" class="reupload-btn"></el-button>
                    </div>
                </div>
                <el-upload v-else class="upload-demo" drag :before-upload="handleFileUpload" :file-list="fileList"
                    multiple ref="upload" action="http://localhost:8000/api/upload/video">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将视频拖到此处，或<span>点击上传</span></div>
                    <div class="el-upload__tip" slot="tip">支持mp4、avi等常见视频格式</div>
                </el-upload>
            </div>
            <div class="button-section">
                <el-button type="primary" size="small" class="action-button button-3" @click="detectVideo"
                    :disabled="!currentVideo" :loading="detecting">
                    <i class="el-icon-video-camera"></i>
                    检测视频
                </el-button>
                <el-button type="success" size="small" class="action-button button-4"
                    @click="openHistoryDialog">
                    <i class="el-icon-time"></i>
                    历史记录
                </el-button>
            </div>
            <div class="result-section">
                <template v-if="detectedVideo">
                    <video controls :src="getVideoUrl(detectedVideo)" class="video-player"></video>
                </template>
                <el-empty v-else :image-size="200"></el-empty>
            </div>
        </div>
        <!-- 右边区域 -->
        <div class="right-panel">
            <div class="description-section">
                <div class="alert-container">
                    <el-empty v-if="!detectionResults.length" :image-size="200"></el-empty>
                    <transition-group v-else name="list" tag="div">
                        <el-alert v-for="alert in detectionResults" :key="alert.time + alert.message"
                            :title="alert.time + getAlertTitle(alert.message)"
                            :type="getAlertType(alert.message)" 
                            :description="getAlertDescription(alert.message)" 
                            :closable="false" 
                            show-icon
                            class="alert-item">
                        </el-alert>
                    </transition-group>
                </div>
            </div>

            <div class="visualization-section" ref="chartContainer">
                <el-empty v-if="!statistics.classes.length" :image-size="200"></el-empty>
                <div v-else id="detectionChart" style="width: 100%; height: 100%;"></div>
            </div>
        </div>

        <!-- 历史记录弹窗 -->
        <el-dialog :visible.sync="historyDialogVisible" title="历史记录" width="50%">
            <el-table :data="formattedVideoHistory" style="width: 100%" @row-click="handleRowClick">
                <el-table-column prop="fileName" label="视频"></el-table-column>
                <el-table-column prop="uploadedAt" label="上传时间"></el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="historyDialogVisible = false">关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { 
  uploadVideo, 
  getUserVideos, 
  detectVideo, 
  getVideoDetections 
} from '@/api/inspection'
import { getVideoLastData, sendDingTalkMessage, getDingTalkConfig } from '@/api/dingtalk'

export default {
    data() {
        return {
            selectedFile: null,
            fileList: [],
            currentVideo: null,
            reuploading: false,
            historyDialogVisible: false,
            videoHistory: [],
            formattedVideoHistory: [],
            detectionResults: [],
            detectedVideo: null,
            statistics: {
                classes: [],
                counts: []
            },
            chart: null,
            detecting: false,
            dingTalkConfig: {
                isActive: false
            }
        };
    },
    methods: {
        async handleUpload(file) {
            const formData = new FormData()
            formData.append('file', file)
            try {
                await uploadVideo(formData)
                this.$message.success('上传成功')
                this.fetchVideos()
            } catch (error) {
                this.$message.error('上传失败')
                console.error('上传失败:', error)
            }
        },

        async fetchVideos() {
            try {
                const response = await getUserVideos()
                if (response && response.code === 1) {
                    this.videos = response.data || []
                } else {
                    this.$message.error((response && response.msg) || '获取视频列表失败')
                }
            } catch (error) {
                console.error('获取视频列表失败:', error)
                this.$message.error('获取视频列表失败')
            }
        },

        async fetchVideoHistory() {
            try {
                const response = await getUserVideos()
                if (response && response.code === 1) {
                    this.videoHistory = response.data || []
                    this.formattedVideoHistory = this.videoHistory.map(video => ({
                        id: video.id,
                        fileName: video.video_name || '未命名视频',
                        uploadedAt: video.uploaded_at
                    }))
                } else {
                    this.$message.error((response && response.msg) || '获取历史记录失败')
                }
            } catch (error) {
                console.error('获取历史记录失败:', error)
                this.$message.error('获取历史记录失败')
            }
        },

        async startDetection(videoId) {
            try {
                await detectVideo(videoId)
                this.$message.success('开始检测')
                this.fetchVideoHistory()
            } catch (error) {
                this.$message.error('启动检测失败')
                console.error('启动检测失败:', error)
            }
        },

        async fetchDetections(videoId) {
            try {
                const response = await getVideoDetections(videoId)
                this.detections = response.data
            } catch (error) {
                this.$message.error('获取检测结果失败')
                console.error('获取检测结果失败:', error)
            }
        },
        handleFileUpload(file) {
            this.selectedFile = file;
            this.fileList.push(file);
            
            // 自动上传文件
            const formData = new FormData();
            formData.append('video', file);

            // 使用API中定义的上传方法
            uploadVideo(formData)
                .then(response => {
                    if (response && response.code === 1) {
                this.$message.success('上传成功');
                this.fetchLatestVideo();
                    } else {
                        this.$message.error((response && response.msg) || '上传失败');
                    }
            })
            .catch(error => {
                    console.error('上传失败:', error);
                this.$message.error('上传失败');
            });

            return false;
        },
        // 视频检测
        async detectVideo() {
            if (!this.currentVideo || !this.currentVideo.id) {
                this.$message.error('未找到当前视频或视频ID')
                return
            }

            try {
                this.detecting = true
                const loading = this.$loading({
                    lock: false,
                    text: '视频检测中...',
                    spinner: 'el-icon-loading',
                    target: '.video-container',
                    background: 'rgba(255, 255, 255, 0.8)',
                    customClass: 'video-loading'
                })

                const response = await detectVideo({ video_id: this.currentVideo.id })
                if (response && response.code === 1) {
                    // 更新检测视频路径
                    this.detectedVideo = response.data.detected_video_path

                    // 处理检测结果
                    this.detectionResults = Array.isArray(response.data.detections)
                        ? response.data.detections
                        : []

                    // 处理统计数据
                    if (response.data.statistics) {
                        // 转换统计数据为数组格式
                        const classes = []
                        const counts = []

                        for (const [className, stats] of Object.entries(response.data.statistics)) {
                            classes.push(className)
                            counts.push(stats.count)
                        }

                        this.statistics = {
                            classes,
                            counts
                        }
                    } else {
                        this.statistics = {
                            classes: [],
                            counts: []
                        }
                    }

                    // 重新渲染图表
                    this.$nextTick(() => {
                        if (this.statistics.classes && this.statistics.classes.length > 0) {
                            this.renderChart()
                        }
                    })

                    loading.close()
                    this.$message.success((response && response.msg) || '检测完成')

                    // 等待2秒后发送钉钉消息
                    if (this.dingTalkConfig.isActive) {
                    setTimeout(async () => {
                        try {
                                const dingResponse = await getVideoLastData()
                                if (dingResponse && dingResponse.code === 1) {
                                await sendDingTalkMessage({
                                    type: 'video',
                                        data: dingResponse.data
                                    })
                            }
                        } catch (error) {
                                console.error('发送钉钉消息失败:', error)
                        }
                        }, 5000)
                    }
                } else {
                    loading.close()
                    this.$message.error((response && response.msg) || '检测失败')
                }
            } catch (error) {
                console.error('视频检测失败:', error)
                this.$message.error('检测失败')
            } finally {
                this.detecting = false
            }
        },

        async fetchDetectionResults(videoId) {
            try {
                const response = await getVideoDetections(videoId)
                if (response && response.code === 1) {
                    this.detectionResults = response.data.detections || []

                    // 确保statistics的格式正确
                    if (response.data.statistics) {
                        this.statistics = {
                            classes: response.data.statistics.classes || [],
                            counts: response.data.statistics.counts || []
                        }
                    } else {
                        this.statistics = { classes: [], counts: [] }
                    }

                    this.$nextTick(() => {
                        this.renderChart()
                    })
                } else {
                    this.$message.error((response && response.msg) || '获取检测结果失败')
                }
            } catch (error) {
                console.error('获取检测结果失败:', error)
                this.$message.error('获取检测结果失败')
            }
        },

        // 渲染统计图表
        renderChart() {
            if (!this.statistics || !this.statistics.classes || !this.statistics.counts) {
                console.log('No statistics data available');
                return;
            }

            const chartDom = document.getElementById('detectionChart');
            if (!chartDom) {
                console.log('Chart container not found');
                return;
            }

            // 如果已存在图表实例，先销毁
            if (this.chart) {
                this.chart.dispose();
            }

            this.chart = echarts.init(chartDom);

            const option = {
                title: {
                    text: '物体检测统计',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: this.statistics.classes || [],
                    axisLabel: {
                        interval: 0,
                        rotate: 30
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '检测次数',
                    minInterval: 1,
                    min: 0,
                    max: Math.max(6, Math.max(...this.statistics.counts)),
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [
                    {
                        name: '检测统计',
                        type: 'bar',
                        data: this.statistics.counts || [],
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#83bff6' },
                                { offset: 0.5, color: '#188df0' },
                                { offset: 1, color: '#188df0' }
                            ])
                        }
                    }
                ]
            };

            this.chart.setOption(option);
        },

        // 获取最新上传的视频
        async fetchLatestVideo() {
            try {
                const response = await getUserVideos()
                if (response && response.code === 1) {
                    const videos = response.data || []
                    if (videos.length > 0) {
                        this.currentVideo = videos[videos.length - 1]

                    if (this.currentVideo.detected_video) {
                            this.detectedVideo = this.currentVideo.detected_video
                            this.fetchDetectionResults(this.currentVideo.id)
                    } else {
                            this.detectedVideo = null
                            this.detectionResults = []
                            this.statistics = { classes: [], counts: [] }
                    }

                        this.reuploading = false
                    }
                } else {
                    this.$message.error((response && response.msg) || '获取视频失败')
                }
            } catch (error) {
                console.error('获取视频失败:', error)
                this.$message.error('获取视频失败')
            }
        },

        getVideoUrl(videoPath) {
            if (!videoPath) return '';
            if (videoPath.startsWith('http')) return videoPath;  // 已经是完整的 URL，直接返回
            return `http://localhost:8000${videoPath.startsWith('/') ? '' : '/'}${videoPath}`;
        },

        handleReupload() {
            this.$message({
                showClose: true,
                message: '请重新上传视频'
            });
            this.clearFiles();
            this.currentVideo = null;
            this.detectedVideo = null;
            this.detectionResults = [];
            this.statistics = { classes: [], counts: [] };
            this.reuploading = true;
        },
        clearFiles() {
            this.selectedFile = null;
            this.fileList = [];
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles();
            } else {
                console.warn("el-upload component is not ready yet.");
            }
        },
        openHistoryDialog() {
            this.historyDialogVisible = true;
            this.fetchVideoHistory();
        },
        handleRowClick(row) {
            this.currentVideo = row;
            const prefixLength = 'http://localhost:8000'.length;
            if (this.currentVideo.video.startsWith('http://localhost:8000')) {
                this.currentVideo.video = this.currentVideo.video.substring(prefixLength);
            }

            // 如果有检测结果，获取并展示
            if (this.currentVideo.detected_video) {
                this.detectedVideo = this.currentVideo.detected_video;
                this.fetchDetectionResults(this.currentVideo.id);
            } else {
                this.detectedVideo = null;
                this.detectionResults = [];
                this.statistics = { classes: [], counts: [] };
            }

            this.reuploading = false;
            this.historyDialogVisible = false;
        },
        getAlertType(message) {
            // 根据不同类型返回不同的警示级别
            if (message.includes('fire')) {
                return 'error';  // 火灾最危险，显示红色
            } else if (message.includes('smoking') || message.includes('shirtless')) {
                return 'warning';  // 吸烟和赤裸上身显示橙色警告
            } else if (message.includes('no_mask')) {
                return 'warning';  // 未戴口罩显示警告
            } else if (message.includes('mouse')) {
                return 'warning';  // 老鼠显示警告
            } else if (message.includes('mask')) {
                return 'success';  // 戴口罩显示绿色成功提示
            } else if (message.includes('person')) {
                return 'info';     // 普通人员显示蓝色信息
            }
            return 'info';  // 默认显示信息类型
        },

        getAlertDescription(message) {
            // 根据不同类型返回不同的描述文字
            if (message.includes('fire')) {
                return '检测到火灾隐患，请立即处理！';
            } else if (message.includes('smoking')) {
                return '检测到吸烟行为，请注意禁烟！';
            } else if (message.includes('shirtless')) {
                return '检测到赤裸上身行为，请注意仪表！';
            } else if (message.includes('no_mask')) {
                return '检测到未佩戴口罩，请及时佩戴！';
            } else if (message.includes('mask')) {
                return '已正确佩戴口罩';
            } else if (message.includes('mouse')) {
                return '检测到老鼠，请注意防范！';
            } else if (message.includes('person')) {
                return '检测到人员活动';
            }
            return message;  // 如果没有匹配则显示原始信息
        },

        getAlertTitle(message) {
            // 根据不同类型返回不同的标题
            if (message.includes('fire')) {
                return '发现火灾隐患';
            } else if (message.includes('smoking')) {
                return '发现吸烟行为';
            } else if (message.includes('shirtless')) {
                return '发现赤裸上身';
            } else if (message.includes('no_mask')) {
                return '发现未戴口罩';
            } else if (message.includes('mask')) {
                return '正确佩戴口罩';
            } else if (message.includes('mouse')) {
                return '发现老鼠';
            } else if (message.includes('person')) {
                return '发现人员';
            }
            return '检测提示';  // 默认标题
        },

        async checkDingTalkConfig() {
            try {
                const response = await getDingTalkConfig()
                if (response.data) {
                    this.dingTalkConfig.isActive = response.data.is_active
                }
            } catch (error) {
                console.error('获取钉钉配置失败:', error)
            }
        }
    },

    created() {
        this.fetchLatestVideo();
        this.checkDingTalkConfig();
    },

    beforeDestroy() {
        // 销毁图表实例
        if (this.chart) {
            this.chart.dispose();
            this.chart = null;
        }

        // 移除窗口调整大小的监听器
        window.removeEventListener('resize', this.chart && this.chart.resize);
    }
};
</script>

<style scoped>
.main-container {
    display: flex;
    height: 100%;
    max-height: 100vh;
    box-sizing: border-box;
    padding: 20px;
    background-color: #f5f7fa;
    gap: 20px;
    overflow: hidden; /* Prevent scrolling in main container */
}

/* 左边区域 */
.left-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    overflow: hidden; /* Prevent scrolling in left panel */
    max-height: calc(100vh - 40px); /* Account for padding */
}

.video-section,
.result-section {
    flex: 1;
    background-color: white;
    border-radius: 8px;
    padding: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    transition: all 0.3s ease;
    min-height: 200px; /* Reduced from 300px */
    max-height: calc((100vh - 120px) / 2); /* Account for parent gaps and button section */
    overflow: hidden; /* Prevent content overflow */
}

.video-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.video-loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
}

.video-loading .el-loading-spinner {
    position: relative;
    top: 0;
    left: 0;
    transform: none;
}

.video-player {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain; /* Changed from cover to contain to avoid overflow */
    border-radius: 8px;
}

.video-overlay {
    position: absolute;
    top: 10px;
    right: 10px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.video-container:hover .video-overlay {
    opacity: 1;
}

.reupload-btn {
    background-color: rgba(255, 255, 255, 0.9);
    border: none;
    color: #409EFF;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.reupload-btn:hover {
    background-color: #409EFF;
    color: white;
}

.button-section {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 0 10px;
    flex-shrink: 0; /* Prevent button section from shrinking */
    height: 40px; /* Fixed height for button section */
}

.action-button {
    min-width: 120px;
    height: 32px;
    padding: 0 15px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    font-size: 13px;
    transition: all 0.2s ease;
}

.action-button i {
    font-size: 14px;
}

.button-3 {
    background-color: #409EFF;
    border-color: #409EFF;
    color: white;
}

.button-4 {
    background-color: #67C23A;
    border-color: #67C23A;
    color: white;
}

.action-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.action-button:disabled {
    background-color: #a0cfff;
    border-color: #a0cfff;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* 右边区域 */
.right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    overflow: hidden; /* Prevent scrolling in right panel */
    max-height: calc(100vh - 40px); /* Account for padding */
}

.alert-container {
    overflow-y: auto;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding-right: 5px; /* Add space for scrollbar */
}

.list-enter-active,
.list-leave-active {
    transition: all 0.5s ease;
}

.list-enter,
.list-leave-to {
    opacity: 0;
    transform: translateX(30px);
}

.alert-item {
    margin-bottom: 10px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.alert-item:hover {
    transform: translateX(5px);
}

.description-section,
.visualization-section {
    flex: 1;
    background-color: white;
    border-radius: 8px;
    padding: 15px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    transition: all 0.3s ease;
    min-height: 200px; /* Reduced from 300px */
    max-height: calc((100vh - 80px) / 2); /* Account for parent gaps */
    overflow: hidden; /* Prevent content overflow */
}

.visualization-section {
    margin-bottom: 0;
}

/* Make sure chart container doesn't overflow */
#detectionChart {
    width: 100% !important;
    height: 100% !important;
    max-height: calc(100% - 20px);
    max-width: 100%;
}

/* 上传区域样式 */
.upload-demo {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.upload-demo .el-upload {
    width: 100%;
    height: 100%;
}

.upload-demo .el-upload-dragger {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 2px dashed #409EFF;
    border-radius: 8px;
    transition: all 0.3s ease;
    max-height: 100%;
    overflow: hidden;
}

.upload-demo .el-upload-dragger:hover {
    border-color: #67C23A;
    background-color: #f5f7fa;
}

.upload-demo .el-icon-upload {
    font-size: 48px;
    color: #409EFF;
    margin-bottom: 16px;
}

.upload-demo .el-upload__text {
    font-size: 16px;
    color: #606266;
}

.upload-demo .el-upload__text span {
    color: #409EFF;
    font-weight: bold;
}

.upload-demo .el-upload__tip {
    margin-top: 8px;
    color: #909399;
    font-size: 14px;
}

/* Fix for the dialog content to prevent it from causing scroll */
.el-dialog__body {
    max-height: 60vh;
    overflow-y: auto;
}

/* Fix for history table */
.el-table {
    max-height: 50vh;
}
</style>